<template name="verifySms">

    <nav-cus  @back="handleNavBack">
    <nav-tips />

  <!-- full page -->
  <view class="verify-gray-container">
    <!-- sms input area -->
    <view id="sms-top">
      <!-- input phone number and send the verify code btn -->
      <view id="sms-top-phone" class="sms-top-sec">    
        <view class="sms-ts-img"><image src="http://beta.gtimg.com/GodIdent/huiyan/img/icon-phonenum.png" /></view>
        <view class="sms-ts-input">
          <input type="number" auto-focus="true" name="phoneNum" @input="phoneNumChanged" maxlength="11" placeholder='请输入手机号码'/>
        </view>
        <view v-if="sms.is60sGap">
          <view class="sms-ts-btn">重新发送 ({{sms.gapSec}}s)</view>
        </view>
        <view v-else>
          <view class="sms-ts-btn sms-ts-btn-enable" v-if="sms.isEnableSendSms" @click="sendVerifyCodeReq">{{sms.sendSmsTtitle}}</view>
          <view class="sms-ts-btn" v-else>{{sms.sendSmsTtitle}}</view>
        </view>
      </view>

      <!-- input the verify code -->
      <view class="sms-top-sec"> 
        <view class="sms-ts-img"><image src="http://beta.gtimg.com/GodIdent/huiyan/img/icon-yzm.png" /></view>
        <view class="sms-ts-input">
          <input type="number"  name="verifyCode" maxlength="4" placeholder='请输入验证码' @input="verifyCodeChanged"/>
        </view>
      </view>
    </view>

    <view class="hint-error">{{sms.hintError}}</view>

    <!-- next btn -->
    <view class="index-btn"> 
      <button type="primary" @click="smsToNext" :disabled="sms.isForbiddenSmsBtn" hover-class='btn-hover'>下一步</button>
    </view>

    <risk-tips />
    <error-toast :isShow="showErrorMsg" :err="err"/>

  </view>
</nav-cus>

</template>

<script>
import riskTips from "../../components/riskTips/riskTips";
import navTips from "../../components/navTips/navTips";
import navCus from "../../components/nav-cus/nav-cus";

import errorToast from "../../components/errorToast/errorToast";
import {
  validate,
  checkNetWork,
  startNativeVerify,
  exitVerify,
  exitVerifyFail,
  $http,
  $common,
  reportError,
  Log
} from "../../utils";
import { tokenExceptionArr } from "../../utils/constant";

export default {
  components: {
    navTips,
    riskTips,
    errorToast,
    navCus
  },
  data() {
    return {
      // sms
      sms: {
        isForbiddenSmsBtn: true, // is Forbidden sms btn
        hintError: "", // error tips
        isEnableSendSms: false, // control is enable click
        is60sGap: false, // control is show interval
        sendSmsTtitle: "获取验证码",
        gapSec: 60, // control the sec
        phoneNum: "",
        verifyCode: ""
      },
      cmsConfig: uni.faceidVerifySdkCmsConfig,
      token: uni.faceidVerifySdkToken,
      baseUrl: uni.faceidVerifySdkBaseUrl,
      curPage: uni.faceidVerifySdkCurPage,
      showErrorMsg: false,
      err: null,
      preClickBtnTime: 0 // previous click time, use to prevent click multiple btn enter multiple same page
    };
  },
  onLoad() {
    console.log("sms onLoad");
    this.cmsConfig = uni.faceidVerifySdkCmsConfig;
    this.baseUrl = uni.faceidVerifySdkBaseUrl;
    this.token = uni.faceidVerifySdkToken;
    this.curPage = uni.faceidVerifySdkCurPage;
  },
  methods: {
    handleNavBack() {
      uni.navigateBack();
    },
    // sms - sendSmsReq
    sendVerifyCodeReq() {
      console.log("sendVerifyCodeReq");
      if (this.isNotAllowClick()) {
        return;
      }
      checkNetWork(() => {
        uni.showLoading({
          title: "短信发送中...",
          mask: true
        });
        $http(
          {
            url: `/api/common/sendSmsCode?BizToken=${this.token}`,
            data: {
              PhoneNum: this.sms.phoneNum
            },
            reTry: {
              tryCount: 3
            }
          },
          res => {
            uni.hideLoading();
            if (res.ErrorCode === 0) {
              // Show interval info
              this.sms.is60sGap = true;
              this.sms.isEnableSendSms = false;
              this.sms.sendSmsTtitle = "重新发送";
              // Start Interval
              var timer60s = setInterval(() => {
                // If Interval finish, clear interval
                if (this.sms.gapSec <= 1) {
                  clearInterval(timer60s);
                  this.sms.is60sGap = false;
                  this.sms.gapSec = 60;
                  // If the phoneNum is OK, enable the resend btn
                  if (validate(this.sms.phoneNum, "sms_phone")) {
                    this.sms.isEnableSendSms = true;
                  }
                }
                this.sms.gapSec = this.sms.gapSec - 1;
              }, 1000);
            } else {
              // 如果出现 14(本次校验已完成) 15 (token过期)的错误，退出验证
              if (tokenExceptionArr.includes(res.ErrorCode)) {
                exitVerifyFail(res);
                return;
              }
              this.sms.hintError = res.ErrorMsg;
              reportError(Log.sendSmsCodeErr, res);
            }
          }
        );
      }, this.showErrorToast);
    },
    // 按钮防抖，需要改造
    isNotAllowClick() {
      var curClickBtnTime = +new Date();
      if (curClickBtnTime - this.preClickBtnTime < 1000) {
        console.log("Click button gap < 1s, not allow exec");
        return true;
      } else {
        this.preClickBtnTime = curClickBtnTime;
        console.log("Click button gap > 1s, allow exec");
        return false;
      }
    },
    phoneNumChanged(e) {
      this.sms.hintError = "";
      var val = e.detail.value;
      // Save the changed phoneNum
      this.sms.phoneNum = val;

      // Check is ok? if OK enable the SendBtn
      var isPhoneOk = validate(val, "sms_phone");
      console.log(`isPhoneOk: ${isPhoneOk}`);

      // If phone ok，and is not gap, set the isEnableSendSms = true
      if (isPhoneOk && !this.sms.is60sGap) {
        this.sms.isEnableSendSms = true;
      }

      // If phoneNumber is fail, disable the send code btn
      if (!isPhoneOk) {
        this.sms.isEnableSendSms = false;
      }

      var isVerifyCodeOk = validate(this.sms.verifyCode, "sms_verifyCode");
      if (isPhoneOk && isVerifyCodeOk) {
        this.sms.isForbiddenSmsBtn = false;
      } else {
        this.sms.isForbiddenSmsBtn = true;
      }
      console.log(`isEnableSendSms: ${this.sms.isEnableSendSms}`);
    },
    // sms - verify code changed
    verifyCodeChanged(e) {
      this.sms.hintError = "";
      this.sms.verifyCode = e.detail.value;
      var isVerifyCodeOk = validate(this.sms.verifyCode, "sms_verifyCode");
      var isPhoneOk = validate(this.sms.phoneNum, "sms_phone");
      if (isPhoneOk && isVerifyCodeOk) {
        this.sms.isForbiddenSmsBtn = false;
      } else {
        this.sms.isForbiddenSmsBtn = true;
      }
    },
    smsToNext() {
      if (this.isNotAllowClick()) {
        return;
      }
      // Confrim that the network is ok
      checkNetWork(() => {
        console.log(this.sms.phoneNum + " | " + this.sms.verifyCode);
        uni.showLoading({
          title: "加载中...",
          mask: true
        });
        $http(
          {
            url: `/api/common/verifySmsCode?BizToken=${this.token}`,
            method: "POST",
            reTry: {
              tryCount: 3
            },
            data: {
              PhoneNum: this.sms.phoneNum,
              VerifyCode: this.sms.verifyCode
            }
          },
          res => {
            uni.hideLoading();
            // If send sms code success
            if (res.ErrorCode === 0) {
              // go next
              var cmsConfig = this.cmsConfig;
              if (cmsConfig.isJustSms) {
                exitVerify({});
              } else {
                var nextPage = "ocr";
                if (cmsConfig.isHideOcrPage) {
                  nextPage = "verifyLivingBody";
                }
                $common.setCurPage({ url: nextPage });
              }
            } else {
              // 如果出现 14(本次校验已完成) 15 (token过期)的错误，退出验证
              if (tokenExceptionArr.includes(res.ErrorCode)) {
                exitVerifyFail(res);
                return;
              }
              this.sms.hintError = res.ErrorMsg;
              reportError(Log.verifySmsCodeErr, res);
            }
          }
        );
      }, this.showErrorToast);
    },
    showErrorToast(err) {
      console.log("showErrorToast err=>", err);
      this.showErrorMsg = true;
      this.err = err;
    }
  }
};
</script>

<style scoped>
.verify-gray-container {
  background-color: #f8f8f8;
}
#sms-top {
  width: 100%;
  background: #fff;
}

.sms-top-sec {
  display: flex;
  align-items: center;
  flex-direction: row;
  height: 52px;
  padding: 0 15px;
}

#sms-top-phone {
  border-bottom: 1px solid rgb(228, 228, 228);
}

.sms-ts-img {
  display: flex;
  align-items: center;
}

.sms-ts-img image {
  height: 25px;
  width: 20px;
  margin-right: 16px;
}
.hint-error {
  padding: 10px;
  color: #ef4b46;
  font-size: 14px;
  height: 19px;
}
.sms-ts-input {
  flex: 1;
}

.sms-ts-btn {
  min-width: 100px;
  text-align: right;
  font-size: 14px;
  color: #888;
  padding: 10px 0;
}

.sms-ts-btn-enable {
  color: #2d72f1;
}
</style>
